import { Reducer } from 'redux';
import { routerRedux } from 'dva/router';
import { Effect } from 'dva';

import { instockList, instockDown } from '@/services/instock';
import { notification } from 'antd';
export interface StateType {
  isRefresh?: boolean;
  total?: number;
  list?: any;
  view?: any;
  edit?: any;
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    list: Effect;
    down: Effect;
  };
  reducers: {
    redList: Reducer<StateType>;
    reFresh: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'instock',

  state: {
    isRefresh: false,
    total: 0,
    list: [],
    view: {},
    edit: {},
  },

  effects: {
    *list({ payload }, { call, put }) {
      try {
        const res = yield call(instockList, payload);
        if (res.status == 200) {
          yield put({
            type: 'redList',
            payload: { data: res.data.content, total: res.data.totalElements },
          });
        }
      } catch (error) {}
    },
    *down({ payload }, { call, put }) {
      try {
        const response = yield call(instockDown, payload);
        const blob = new Blob([response], {
          type:
            'application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
        }); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
        const downloadElement = document.createElement('a');
        const href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = '库存管理.xlsx'; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
      } catch (error) {}
    },
  },

  reducers: {
    redList(state, { payload }) {
      return {
        ...state,
        list: payload.data,
        total: payload.total,
        isRefresh: false,
      };
    },
    reFresh(state, { payload }) {
      return {
        ...state,
        isRefresh: payload,
      };
    },
  },
};

export default Model;
